package com.itheima.d4_algorithm;

import javax.swing.plaf.SpinnerUI;

/**
 * 目标：掌握二分查找算法。
 * <p>
 * binarySearch
 */
public class Test3 {
    public static void main(String[] args) {
        int[] arr = {2, 7, 12, 34, 82, 89, 98, 126, 145, 199, 324, 453};
        int data = 82;
        int rs = find(arr, data);
        if (rs != -1) {
            System.out.println("找到了，索引是：" + rs);
        } else {
            System.out.println("没找到");
        }

    }

    public static int find(int[] arr, int data) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int middle = (left + right) / 2;
            if (data > arr[middle]) {
                left = middle + 1;
            } else if (data < arr[middle]) {
                right = middle - 1;
            } else {
                return middle;
            }
        }
        return -1;

    }
}
